<template>
  
  <scroll-view class="page-container" scroll-y="true" style="height: calc(100vh - 100rpx);">
    <view class="calendar-content" v-if="showCalendar">
      <view class="calen">
        <uni-calendar 
          class="custom-calendar" 
          :selected="selectedDates" 
          :showMonth="false"
          @change="handleDateChange"
          :dateCellContent="dateCellContent"
        />
      </view>
    </view>

    <view class="nav-items-container">
      <view 
        class="nav-item" 
        v-for="(item, index) in filteredAppointments" 
        :key="index"
        @click="handleServiceItemClick(item)"
      >
        <view class="item-content">
          <text class="thing">{{ item.serviceName }}</text>
          <text class="time">{{ formatTime(item.appointmentDate, item.startTime, item.endTime) }}</text>
        </view>
      </view>
    </view>

    <view v-if="filteredAppointments.length === 0 && selectedDate" class="no-appointment-tip">
      <text>当前日期没有预约记录</text>
    </view>
  </scroll-view>
  
  <view class="nurse-tabbar">
    <view 
      v-for="(item, index) in tabList" 
      :key="index" 
      class="tab-item"
      :class="{ active: currentIndex === index }"
      @click="handleTabClick(index)"
    >
      <image :src="currentIndex === index ? item.selectedIconPath : item.iconPath" class="tab-icon" />
      <text class="tab-text">{{ item.text }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getCaregiverAssignmentList } from '@/api/nurse/caregiverassignment'

const showCalendar = ref(true)
const selectedDates = ref([])
const appointments = ref([])
const filteredAppointments = ref([])
const archiveId = ref(uni.getStorageSync('archiveId'))
const checkLogin = ref(uni.getStorageSync('nurseisLoggedIn'))
const selectedDate = ref(null) // 新增当前选中日期

const tabList = ref([
  {
    iconPath: '../../../static/tabbar/home.png',
    selectedIconPath: '../../../static/tabbar/homeHL.png',
    text: '首页',
    pagePath: '/pages/nurse-platform/index/index'
  },
  {
    iconPath: '../../../static/tabbar/exampleHL.png',
    selectedIconPath: '../../../static/tabbar/exampleHL.png',
    text: '预约日历',
    pagePath: '/pages/nurse-platform/order/order'
  },
  {
    iconPath: '../../../static/tabbar/personal.png',
    selectedIconPath: '../../../static/tabbar/personalHL.png',
    text: '个人中心',
    pagePath: '/pages/nurse-platform/my/my'
  }
]);

const currentIndex = ref(1);

// 自定义日历单元格内容
const dateCellContent = ({ date, isSelected }) => {
  const hasAssignment = selectedDates.value.some(item => item.date === date)
  if (hasAssignment) {
    return {
      top: '有排班',
      topStyle: {
        color: '#ff0000',
        fontSize: '12px'
      }
    }
  }
  return null
}

// 获取护工排班列表
const fetchCaregiverAssignments = async () => {
  try {    const res = await getCaregiverAssignmentList({ caregivergId: archiveId.value })
    if (res.code === 200) {
      const currentDate = new Date().toISOString().split('T')[0] // 获取当前日期
      console.log('[DEBUG] API返回数据:', res.data) // 添加日志
      // 转换 selectedDates 为 uni-calendar 需要的格式
      selectedDates.value = res.data.flatMap(item => {
        const startDate = new Date(item.serviceStartDate)
        const endDate = new Date(item.serviceEndDate)
        const dates = []
        for (let d = startDate; d <= endDate; d.setDate(d.getDate() + 1)) {
          const dateStr = d.toISOString().split('T')[0]
          // 只添加当前日期及之后的排班
          if (dateStr >= currentDate) {
            dates.push({
              date: dateStr,
              info: '有排班',
              data: {
                serviceName: item.serviceName || '未命名服务',
                startTime: item.serviceStartTime,
                endTime: item.serviceEndTime,
                orderId: item.orderId,
                status: item.status || 'PENDING_CONFIRM', // 添加状态字段，默认为待确认

                status: item.status, // 添加状态字段
                status: item.status,
                startDate: item.serviceStartDate,
                endDate: item.serviceEndDate
              }
            })
          }
        }
        return dates
      })

      // 默认选中当前日期
      selectedDate.value = currentDate
      handleDateChange({ fulldate: currentDate })
    }
  } catch (err) {
    console.error('获取护工排班列表失败:', err)
  }
}

// 检查登录状态
const checkLoginStatus = () => {
  const isLoggedIn = uni.getStorageSync('nurseisLoggedIn')
  if (!isLoggedIn) {
    uni.showModal({
      title: '提示',
      content: '您还未登录，请先登录',
      confirmText: '去登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/login/index'
          })
        }
      }
    })
    return false
  }
  return true
}

// 处理日期选择
const handleDateChange = (e) => {
  selectedDate.value = e.fulldate
  if (selectedDate.value) {
    // 修改过滤逻辑，确保获取正确状态
    filteredAppointments.value = selectedDates.value
      .filter(item => item.date === selectedDate.value)      .map(item => {
        const mappedItem = {
          ...item.data,
          serviceName: item.data.serviceName,
          appointmentDate: selectedDate.value,
          startTime: item.data.startTime,
          endTime: item.data.endTime,
          startDate: item.data.startDate,
          endDate: item.data.endDate,
          status: item.data.status
        }
        console.log('[DEBUG] 映射后的预约项:', mappedItem)
        console.log('[DEBUG] 状态值:', mappedItem.status)
        return mappedItem
      })
  }
}

// 格式化时间显示
const formatTime = (date, startTime, endTime) => {
  return `${date} ${startTime} - ${endTime}`
}

const handleTabClick = (index) => {
  if (currentIndex.value !== index) {
    currentIndex.value = index;
    uni.reLaunch({ url: tabList.value[index].pagePath });
  }
};

const handleServiceItemClick = (item) => {
  console.log('[DEBUG] 跳转前的完整数据:', item)
  console.log('[DEBUG] 跳转前的状态值:', item.status)
  uni.navigateTo({
    url: `/pages/nurse-platform/order/detail?data=${encodeURIComponent(JSON.stringify({
      ...item,
      // 确保传递时间、日期和服务状态
      startDate: item.startDate,
      endDate: item.endDate,
      startTime: item.startTime,
      endTime: item.endTime,
      status: item.status,
      orderId: item.orderId
    }))}`
  });
};

// 在页面加载时获取数据
onMounted(() => {
  if (checkLoginStatus()) {
    fetchCaregiverAssignments()
  }
})

onShow(() => {
  const isLoggedIn = uni.getStorageSync('nurseisLoggedIn');
  if (!isLoggedIn) {
    uni.showModal({
      title: '提示',
      content: '您还未登录，请先登录',
      confirmText: '去登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/login/index'
          });
        }
      }
    });
  }
  currentIndex.value = 1;
});
</script>

<style lang="scss">
.custom-calendar {
  width: 100%;
  height: 29rpx;

  .uni-calendar__header,
  .uni-calendar__content {
    font-size: 36rpx !important;
  }

  .uni-calendar__weeks {
    padding: 5rpx !important;
  }

  .uni-calendar__week-day {
    width: 45px !important;
    height: 30px !important;
    line-height: 45px !important;
  }
}

.page-container {
  height: 100vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding-top: auto;
}

.calendar-content {
  padding: 20rpx;
}

.nav-items-container {
  padding: 20rpx;
}

.nurse-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100rpx;
  background-color: #F8F8F8;
  border-top: 1rpx solid #e5e5e5;
}

.tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.tab-icon {
  width: 48rpx;
  height: 48rpx;
}

.tab-text {
  font-size: 24rpx;
  color: #666;
}

.tab-item.active .tab-text {
  color: #018d71;
}

.nav-item {
  background-color: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  padding: 24rpx;
  transition: transform 0.2s ease;

  &:active {
    transform: scale(0.98);
  }
}

.item-content {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.thing {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.time {
  font-size: 28rpx;
  color: #666;
}

.no-appointment-tip {
  text-align: center;
  padding: 40rpx;
  font-size: 28rpx;
  color: #999;
}
</style>